import * as THREE from 'three';
import { getTexture, getPos, cameraFarAuto } from '@/utils/three/utils';
import { Water } from 'three/examples/jsm/objects/Water.js';
import React, { useRef, useState, useEffect } from 'react';
import SceneMap from '@/utils/three/index';

import bqj from '@/assets/images/bqj.png';
import waterNormals from '@/assets/images/water-normals.jpg';

export function FirstScreen() {
  const renderRef = useRef<HTMLElement>(null);
  const map = useRef<any>(null);
  const water = useRef<any>(null);
  const cameraPos = useRef<any>(null);

  const init = async () => {
    map.current = new SceneMap(renderRef.current);
    map.current!.init();
    map.current!.addControls();

    const waterGeometry = new THREE.PlaneGeometry(
      renderRef.current!.clientWidth * 0.2,
      renderRef.current!.clientHeight * 0.2
    );
    water.current = new Water(waterGeometry, {
      textureWidth: 1024, // 提高分辨率
      textureHeight: 1024,
      waterNormals: await getTexture(waterNormals),
      sunDirection: new THREE.Vector3(),
      sunColor: 0xffffff,
      waterColor: 0x001e0f,
      distortionScale: 1.3,
      fog: map.current.fog !== undefined
    });
    water.current!.rotation.x = -Math.PI / 2;
    map.current!.addMesh(water.current);
    map.current!.renderAdd(waterAni);

    const { x, y, z } = cameraFarAuto(map.current!.camera, water.current);
    map.current!.camera.position.set(x, z, y);
    map.current!.camera.lookAt(water.current);

    const geometry = new THREE.BoxGeometry(664 * 0.22, 1313 * 0.22, 1);
    const material = new THREE.MeshBasicMaterial({
      map: await getTexture(bqj, { repeat: { x: -1, y: 1 }, colorSpace: true })
    });
    const cube = new THREE.Mesh(geometry, material);
    cube.rotation.x = -Math.PI / 2;
    console.log( z)
    cube.position.set(0, z * 1.5, 0);
    map.current!.addMesh(cube);
  };

  const waterAni = () => {
    water.current.material.uniforms['time'].value += 1.0 / 60.0;
  };

  useEffect(() => {
    init();
  }, []);

  return (
    <main ref={renderRef} style={{ width: '100vw', height: '100vh' }}></main>
  );
}
